package com.lupan.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Properties;

/**
 * 说明：kafka发送消息的工具类
 *
 * @author lupan
 * @version 2016/10/25 10:42
 */

@Component
public class MyKafkaProducer {

    private static Logger logger = LoggerFactory.getLogger(MyKafkaProducer.class);

    @Value("#{config['kafka.topic']}")
    private String topic ;
    @Value("#{config['kafka.server']}")
    private String kafkaServer;

    private Producer<String, byte[]> producer;

    @PostConstruct
    public void init() {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName());
        producer = new KafkaProducer<>(props);
    }

    @PreDestroy
    public void destroy(){
        producer.close();
    }

    /**
     * 发送卡夫卡消息
     * @param content 消息内容
     */
    public void send(String content) {
        logger.info("Send {} topic message:{}", topic, content);
        try{
            ProducerRecord<String, byte[]> record = new ProducerRecord<>(topic,content.getBytes());
            producer.send(record);
        }catch (Exception e){
            logger.error("Send {} topic message:{} failed!",topic, content);
            e.printStackTrace();
            throw new RuntimeException("Send kafka message failed!");
        }
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }
}
